from flask import Blueprint, jsonify, request
from config.config import db
import json

# 创建 Blueprint，命名为 'users'
users_bp = Blueprint("users", __name__)


# 对象模板(单表对象)(不灵活，不建议使用)
class UserModel(db.Model):
    __tablename__ = "tb_img"
    img_id = db.Column(db.Integer, primary_key=True)
    img_title = db.Column(db.String(100))
    img_date = db.Column(db.String(10))

    def to_dict(self):
        return {"img_id": self.img_id, "img_date": self.img_date}


# 用户对象(比如多表查询可以用类似此对象接收)
class UserObj:
    def __init__(self, img_id, user_id, img_date, img_path, note):
        self.img_id = img_id
        self.user_id = user_id
        self.img_date = img_date
        self.img_path = img_path
        self.note = note

    def to_json(self):
        return {
            "img_id": self.img_id,
            "user_id": self.user_id,
            "img_date": self.img_date,
            "img_path": self.img_path,
            "note": self.note,
        }

#  将list数据转换为list对象
def convert_userobj(data):
    return [UserObj(e[0], e[1], e[2], e[3], e[4]) for e in data]


# 定义接口返回数据序列化
class UserRes:
    def __init__(self, userObj, page):
        self.userObj = userObj
        self.page = page

    def to_json(self):
        return {
            "users": {"img_id": self.userObj.img_id, "img_date": self.userObj.img_date},
            "page": self.page,
        }

    def to_json_list(self):
        return {
            "users": self.userObj,
            "page": self.page,
        }


# 获取用户列表
@users_bp.route("/getUser", methods=["GET"])
def getUser():
    # userlist = UserModel.query.filter(User.img_id).all()
    # users_dict = [user.__dict__ for user in userlist]
    # user = User.query.get_or_404(47)
    stmt = db.text("SELECT * FROM tb_img WHERE img_id = :img_id")
    result = db.session.execute(stmt, {"img_id": 47})
    user = result.fetchone()  # 获取单个结果
    page = request.args.get("page", default=1, type=int)
    userRes = UserRes(user, page)
    return jsonify(userRes.to_json())


# 获取用户列表
@users_bp.route("/getUserList", methods=["GET"])
def getUserList():
    # userAll = User.query.filter(User.img_id).all()
    stmt = db.text("SELECT img_id,user_id,img_date,img_path,note FROM tb_img")
    result = db.session.execute(stmt)
    queryResList = result.fetchall()
    # 将查询结果转为对象集合
    userObjs = convert_userobj(queryResList)
    # 修改属性
    for userObj in userObjs:
        userObj.user_id = 123456
    # 序列化返回
    serializable = [row.to_json() for row in userObjs]
    userList = json.dumps(serializable)
    page = request.args.get("page", default=1, type=int)
    # 构建返回对象
    userRes = UserRes(userList, page)
    return jsonify(userRes.to_json_list())


# 添加新用户
@users_bp.route("/addUser", methods=["POST"])
def addUser():
    # username = request.form.get('username')
    new_user = request.get_json()
    # 模拟数据
    users = [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]
    users.append(new_user)
    return jsonify({"message": "用户添加成功", "user": new_user})
